<template>
  <view class="page">
    <!-- 顶部区域 -->
    <view class="header">
    </view>

    <view class="content">
      <view class="version-card">
        <view class="version-info">
          <text class="label">当前版本</text>
          <text class="version">v{{ currentVersion }}</text>
        </view>
        
        <view class="update-status" v-if="checking">
          <uni-load-more status="loading" :iconSize="18" />
        </view>
        <view class="update-status" v-else>
          <view v-if="hasUpdate" class="has-update">
            <text class="update-text">发现新版本 {{ latestVersion }}</text>
            <button class="update-btn" @click="handleUpdate">立即更新</button>
          </view>
          <view v-else class="no-update">
            <image class="status-icon" src="../../static/images/shangchuan.png" />
            <text class="status-text">已是最新版本</text>
          </view>
        </view>
      </view>

      <button class="check-btn" :disabled="checking" @click="checkUpdate">
        <text>检查更新</text>
      </button>
    </view>
  </view>
</template>

<script>
import { _updateAndGetLatestVersion } from '@/service/version.js'
import manifest from '../../manifest.json'

export default {
  data() {
    return {
      currentVersion: '',
      latestVersion: '',
      checking: false,
      hasUpdate: false,
      updateDescription: '',
      brief: ''
    }
  },
  onReady() {
    // 确保组件已经挂载完成
    this.getCurrentVersion()
  },
  onLoad() {
    // 页面加载时就获取当前版本
    this.getCurrentVersion()
  },
  methods: {
    // 获取当前版本
    getCurrentVersion() {
      try {
        // 从manifest.json获取版本号
        const version = manifest.versionName || manifest.version
        if (version) {
          this.currentVersion = version
          console.log('从manifest获取到当前版本号:', this.currentVersion)
          this.checkUpdate()
          return
        }

        // 如果manifest中没有版本号，则使用默认版本
        console.warn('manifest中未找到版本号，使用默认版本号')
        this.currentVersion = '1.0.0'
        this.checkUpdate()
      } catch (e) {
        console.error('获取版本号失败:', e)
        this.currentVersion = '1.0.0'
        this.checkUpdate()
      }
    },

    // 检查更新
    async checkUpdate() {
      if (this.checking) return
      this.checking = true
      
      try {
        const res = await this.getLatestVersion()
        console.log('获取到最新版本信息:', res)
        
        if (!res || !res.data) {
          throw new Error('获取版本信息失败')
        }

        const latestVersion = res.data.version
        this.latestVersion = latestVersion
        this.brief = res.data.brief
        this.updateDescription = res.data.brief

        // 版本号比较
        const currentVersionNum = this.currentVersion.replace('v', '')
        console.log('版本比较:', currentVersionNum, latestVersion)
        
        // 确保两个版本号都存在再进行比较
        if (currentVersionNum && latestVersion) {
          const compareResult = this.compareVersion(currentVersionNum, latestVersion)
          console.log('版本比较结果:', compareResult)
          this.hasUpdate = compareResult < 0
        }
      } catch (error) {
        console.error('检查更新失败:', error)
        uni.showToast({
          title: '检查更新失败',
          icon: 'none'
        })
      } finally {
        this.checking = false
      }
    },

    // 获取最新版本
    async getLatestVersion() {
      try {
        const res = await _updateAndGetLatestVersion()
        console.log('服务器返回的版本信息:', res)
        return res
      } catch (error) {
        console.error('获取最新版本失败:', error)
        throw error
      }
    },

    // 版本号比较
    compareVersion(v1, v2) {
      // 移除可能存在的'v'前缀
      v1 = v1.replace('v', '')
      v2 = v2.replace('v', '')
      
      const v1Parts = v1.split('.').map(Number)
      const v2Parts = v2.split('.').map(Number)
      
      for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
        const v1Part = v1Parts[i] || 0
        const v2Part = v2Parts[i] || 0
        
        if (v1Part < v2Part) return -1
        if (v1Part > v2Part) return 1
      }
      return 0
    },

    // 处理更新
    handleUpdate() {
      uni.navigateTo({
        url: '/pages/update/update',
        success: (res) => {
          res.eventChannel.emit('updateInfo', {
            currentVersion: this.currentVersion,
            latestVersion: this.latestVersion,
            description: this.updateDescription,
            forceUpdate: false
          })
        },
        fail: (error) => {
          console.error('跳转失败:', error)
          uni.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background-color: #f7f7f7;
}

.header {
  //background: linear-gradient(180deg, #138f87 0%, #44cdbd 100%);
  padding: 0 32rpx 120rpx;

  .header-title {
    color: #fff;
    font-size: 36rpx;
    font-weight: 500;
  }
}

.content {
  margin-top: -80rpx;
  padding: 0 32rpx;
  position: relative;
  z-index: 1;
}

.version-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);
  margin-bottom: 32rpx;

  .version-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32rpx;

    .label {
      font-size: 28rpx;
      color: #666;
    }

    .version {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }

  .update-status {
    text-align: center;
    padding: 32rpx 0;

    .has-update {
      .update-text {
        font-size: 30rpx;
        color: #138f87;
        font-weight: 500;
        margin-bottom: 24rpx;
        display: block;
      }

      .update-btn {
        background: #138f87;
        color: #fff;
        font-size: 28rpx;
        padding: 16rpx 48rpx;
        border-radius: 44rpx;
        border: none;
        
        &:active {
          background: #44cdbd;
        }
      }
    }

    .no-update {
      display: flex;
      flex-direction: column;
      align-items: center;
      .status-icon {
        width: 160rpx;
        height: 120rpx;
        margin-bottom: 24rpx;
      }

      .status-text {
        font-size: 30rpx;
        color: #999;
      }
    }
  }
}

.check-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #fff;
  color: #138f87;
  font-size: 32rpx;
  border-radius: 44rpx;
  border: 2rpx solid #138f87;
  margin-top: 32rpx;
  
  &:active {
    background: #f0f0f0;
  }
  
  &[disabled] {
    background: #f5f5f5;
    border-color: #ddd;
    color: #999;
  }
}
</style>